<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchemaAuth } from './menu.data';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { addModuleAuthApi, updateModuleAuthApi } from '/@/api/admin/auth';

  export default defineComponent({
    name: 'PostDrawer',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const updateId = ref();
      const systemFlag = ref();
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchemaAuth,
        showActionButtonGroup: false,
      });
      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;
        updateId.value = data?.record.moduleId;
        updateSchema({
          field: 'dictType',
          label: '类型',
          dynamicDisabled: unref(isUpdate),
          component: 'Input',
        });
        if (unref(isUpdate)) {
          systemFlag.value = data?.record.systemFlag;
          setFieldsValue({
            ...data.record,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '添加权限' : '编辑权限'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          values.moduleId = updateId.value;
          values.roleIds = values.roleIds ?? [];
          const apiFn = unref(isUpdate) ? updateModuleAuthApi : addModuleAuthApi;
          await apiFn(values);
          // updatePost
          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
      };
    },
  });
</script>
